#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

int fd;

void handler(int sig)
{
    int status;
    pid_t pid = waitpid(-1, &status, WNOHANG);
    char buf[50];
    snprintf(buf, 50, "[SIGCHLD] Child %d exited with status %d\n", pid, WEXITSTATUS(status));
    write(fd, buf, strlen(buf));
}

int main()
{
    fd = open("sigchld.log", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    write(fd, "=== Zombie Prevention Test ===\n", 32);

    signal(SIGCHLD, handler);
    pid_t pid = fork();

    if (pid == 0)
    {
        write(fd, "[CHILD] Aborting...\n", 20);
        abort(); // 子进程异常退出
    }
    else
    {
        sleep(2);
        write(fd, "[PARENT] Exiting\n", 17);
    }

    close(fd);
    return 0;
}